	package com.adb.receivecontent.utility;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class SpliteLargeFiles {
	
	public ArrayList<String> chunkFileList;
	
	public SpliteLargeFiles(){
		chunkFileList = new ArrayList<String>();
	}
	
	public ArrayList<String> FragmentFiles(String sourceFileName,int CHUNK_SIZE){
			
			File mFileWillBeRead = new File(sourceFileName);
			int FILE_SIZE = (int)mFileWillBeRead.length();
			int NUMBER_CHUNK = 0;
			byte[] tempBuffer =  null;
			InputStream mInputStream = null;
			int totalByteRead = 0;
		try{
			
			mInputStream = new BufferedInputStream(new FileInputStream(mFileWillBeRead));
			
			while(totalByteRead < FILE_SIZE){
				
				String CHUNK_PART_NAME = "data" + NUMBER_CHUNK + ".bin";
				int bytesRemain = FILE_SIZE - totalByteRead;
				if(bytesRemain < CHUNK_SIZE){
					//Remaining data part is smaller than the CHUNK_SIZE
					CHUNK_SIZE = bytesRemain;
				}
				
				tempBuffer = new byte[CHUNK_SIZE];
				int byteRead = mInputStream.read(tempBuffer,0,CHUNK_SIZE);
				if(byteRead > 0){
					totalByteRead += byteRead;
					NUMBER_CHUNK++;
				}
				
				write(tempBuffer, Const.CACHE_HOME + "/" + CHUNK_PART_NAME);
				chunkFileList.add(Const.CACHE_HOME + "/" + CHUNK_PART_NAME);
				
			}
			
			mInputStream.close();
			
			
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			
		}
		
		return chunkFileList;
	}
	
	void write(byte[] DataByteArray, String DestinationFileName){
	     try {
	       OutputStream output = null;
	       try {
	         output = new BufferedOutputStream(new FileOutputStream(DestinationFileName));
	         output.write( DataByteArray );
	         System.out.println("Writing Process Was Performed");
	       }
	       finally {
	         output.close();
	       }
	     }
	     catch(Exception ex){
	      ex.printStackTrace();
	     }
	 }
	
	
}
